import React, { useState, useEffect, memo, useMemo } from 'react'
import { Table, Divider, message, Button, Popconfirm, Input, Select } from 'antd';
import { BasicLayout } from '@components/layout';
import api from '@request/api_import';
import './index.less';
import createApiModal from './create_api_modal/index';
import {apiTypes} from '../mock';

const pageSize = 20;
const Option = Select.Option;
export interface APIRecord {
  access_type: string,
  create_time: string,
  desc: string,
  id: number,
  name: string,
  type: string,
  update_time: string,
  version: string,
  request_info: {
    method?: string,
    url?: string,
    endpoint?: string,
    model_name?: string,
    token?: string
  }
}
interface DataList {
  totalNum?: number,
  list?: APIRecord[],
  current?: number
}
interface requestParams {
  currentPageNum?: number,
  curKeyword?: string,
}
interface request {
  current_page_num?: number,
  name?: string,
  page_size?: number,
  type?: string
}
const ApiImport = () => {
  const [loading, setLoading] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [keyword, setKeyword] = useState<string>('');
  const [type, setType] = useState<string | undefined>(undefined);
  const [data, setData] = useState<DataList>({});
  useEffect(() => {
    getList();
  }, []);
  const getList = (requests: requestParams = {}) => {
    const { currentPageNum, curKeyword } = requests;
    let params: request = {
      page_size: pageSize,
      current_page_num: currentPageNum || pageNum,
      name: keyword.trim()
    };
    if(curKeyword || curKeyword === '') params.name = curKeyword.trim();
    if (type) params.type = type;
    setLoading(true);
    api.getApiList({
      params: params
    })
      .then(res => {
        setData(() => {
          return {
            totalNum: res.count_num,
            list: res.data,
            current: res.current_page_num
          }
        })
      })
      .finally(() => {
        setLoading(false);
      })
  }
  const columns = useMemo(() => {
    return [
      {
        dataIndex: 'name',
        title: 'API名称'
      },
      {
        dataIndex: 'type',
        title: '类型',
        render: (text: string) => {
          let info = apiTypes.find(item => item.key === text);
          return info?.name
        }
      },
      {
        dataIndex: 'access_type',
        title: '接入方式'
      },
      {
        dataIndex: 'desc',
        title: '描述'
      },
      {
        dataIndex: 'create_time',
        title: '创建时间'
      },
      {
        dataIndex: '',
        title: '操作',
        render: (_text: '', record: APIRecord) => {
          return <div>
            <a onClick={() => openApiModal('view', record)}>查看</a>
            <Divider type="vertical" />
            <a onClick={() => openApiModal('edit', record)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm
              title={`确定删除${record.name}吗？`}
              onConfirm={() => deleteApi(record)}
            >
              <a >删除</a>
            </Popconfirm>
          </div>
        }
      }
    ];
  }, [])
  const deleteApi = async (record: APIRecord) => {
    try {
      await api.deleteApiById({
        query: {
          id: record.id
        }
      })
      message.success('删除成功')
      getList({currentPageNum: 1});
    } catch (err) {
      message.error('删除失败')
    }
  }
  const openApiModal = (type: string, record: APIRecord | {} = {}) => {
    createApiModal({
      type,
      record,
      getList
    })
  }
  const search = (value: string) => {
    setKeyword(value);
    getList({curKeyword: value});
  }
  const { totalNum, list } = data;
  return (
    <BasicLayout
      className='api-import'
      title='API管理'
      addButton={
        <Button type='primary' onClick={() => openApiModal('add', {})}>新建API</Button>
      }
      extra={
        <>
          <Input.Search
            onChange={(e) => search(e.target.value)}
            value={keyword}
            onSearch={(value) => search(value)}
          />
        </>
      }
    >
      <Table
        columns={columns}
        dataSource={list}
        loading={loading}
        scroll={{ y: `calc(100vh - 300px)` }}
        bordered
        pagination={{
          total: totalNum,
          pageSize: pageSize,
          showQuickJumper: true,
          showSizeChanger: false,
          showTotal: (total) => `总共${total}条`,
          current: pageNum,
          onChange: (page, pageSize) => {
            setPageNum(page);
            getList({ currentPageNum: page})
          }
        }}
      />
    </BasicLayout>
  )
}

export default memo(ApiImport);